import pygame
import sys
import random


class Ball(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("../res/image/imonilas.png")
        self.rect = self.image.get_rect()
        self.x = random.randint(0, 30)
        self.y = random.randint(0, 30)

    def chage_color(self, color):
        self.image.fill(color, special_flags=pygame.BLEND_ADD)

    def move_by_self(self, width, height):
        if self.rect.left < 0 or self.rect.right > width:
            self.x *= -1
        self.rect.x += self.x
        if self.rect.top < 0 or self.rect.bottom > height:
            self.y *= -1
        self.rect.y += self.y


def main():
    pygame.init()
    size = width, height = 640, 480
    screen = pygame.display.set_mode(size)
    # 设置标题
    pygame.display.set_caption("Ball Sprites")
    color = (0, 0, 0)

    ball1 = Ball()
    ball2 = Ball()
    ball2.chage_color((200, 0, 0))
    ball2.rect.x = 320
    ball2.rect.y = 240
    #ball3 = Ball()
    #ball3.chage_color((0, 200, 200))
    #ball3.rect.x = 320
    #ball3.rect.y = 240

    goodBalls = pygame.sprite.Group()
    goodBalls.add(ball1)

    badBalls = pygame.sprite.Group()
    badBalls.add(ball2)
    #badBalls.add(ball3)

    meet_time = 0

    clock = pygame.time.Clock()
    while True:
        clock.tick(5)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        ball1.move_by_self(width, height)
        ball2.move_by_self(width, height)
        #ball3.move_by_self(width, height)

        for badball in badBalls.sprites():
            if pygame.sprite.collide_circle(ball1, badball):
                meet_time += 1
                print("You Lose {} times!".format(meet_time))

        screen.fill(color)
        goodBalls.draw(screen)
        badBalls.draw(screen)
        pygame.display.update()
    pygame.quit()


if __name__ == '__main__':
    main()
